<?php
class DigCms_Library_Validate_ParentItem extends Zend_Validate_Abstract
{
    const SAME = 'same';
    const CIRCULAR = 'circular';
    
    protected $_messageTemplates = array(
        self::SAME     => 'You can not set an item to be its own parent.',
        self::CIRCULAR => 'The parent you selected for this item creates a circular reference.'
    );
    
    public function isValid($value, $context = null)
    {
        if($value == 0) {
            return true;
        }
        $currentItem = DigCms_Model_Item::factory($context['id']);
        $parentItem = DigCms_Model_Item::factory($value);
        
        if($value == $currentItem->id) {
            $this->_error(self::SAME);
            return false;
        }
        
        $parentParents = $parentItem->parents();
        if($parentParents) {
            foreach ($parentParents as $parentsParent) {
                if($parentsParent->id == $currentItem->id) {
                    $this->_error(self::CIRCULAR);
                    return false;
                }
            }
        }
        return true;
    }
}
?>